package com.shenmazg6.filter;

import com.alibaba.fastjson2.JSON;
import com.shenmazg6.utils.ResultResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author 军哥
 * @version 1.0
 * @description: MyGobalFilter
 * @date 2022/12/19 15:36
 */

@Configuration
public class MyGobalFilter implements GlobalFilter, Ordered {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    public Mono<Void> returnError(ServerHttpResponse response, int code, String message) {

        ResultResponse failed = ResultResponse.FAILED(code, message);
        String msg = JSON.toJSONString(failed);

        DataBuffer dataBuffer = response.bufferFactory().wrap(msg.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(dataBuffer));
    }


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 获取Request、Response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 解决中文乱码问题
        HttpHeaders headers = response.getHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 获取URL/放行白名单
        String requestUrl = exchange.getRequest().getURI().getRawPath();
        System.out.println(requestUrl);
        System.out.println(request.getURI());
        if(requestUrl.contains("/user/login")) {
            return chain.filter(exchange);
        }

        // 检查token
        String token = request.getHeaders().getFirst("token");
        if(token == null) {
            return returnError(response, 403, "token无效");
        }
        String redisToken = (String)redisTemplate.opsForValue().get(token);
        if(redisToken==null || !token.equals(redisToken)) {
            return returnError(response, 403, "token错误");
        }

        // token续期
        redisTemplate.opsForValue().set(token, token, 30, TimeUnit.MINUTES);


        // 放行
        return chain.filter(exchange);
    }

    /**
     * 控制过滤器的顺序
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
